package com.example;

import com.example.config.modbus.Modbus4jUtils;
import com.example.config.modbus.Modbus4jWriteUtils;
import com.example.config.modbus.Register;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.ModbusSlaveSet;
import com.serotonin.modbus4j.code.DataType;
import com.serotonin.modbus4j.exception.ErrorResponseException;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.ip.tcp.TcpSlave;

public class Main {
    public static void main(String[] args) throws ModbusInitException, ModbusTransportException, ErrorResponseException {
        try {
            run();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ModbusMaster master = Modbus4jUtils.getMaster("127.0.0.1", 502);
        Modbus4jWriteUtils.writeHoldingRegister(master, 1, 9, 607, DataType.TWO_BYTE_INT_SIGNED);
    }

    public static void run() throws InterruptedException {
        new Thread(() -> {
            createSalve();
        }).start();
        Thread.sleep(1000);
        // InitModbusSlave();
    }

    public static void createSalve() {
        ModbusSlaveSet slaveSet = new TcpSlave(502, false);

        // 向过程影像区添加数据
        slaveSet.addProcessImage(Register.getModbusProcessImage(1));

        // 获取寄存器
        slaveSet.getProcessImage(1);

        try {
            slaveSet.start();
            System.out.println("Modbus slave started.");
        } catch (ModbusInitException e) {
            e.printStackTrace();
        }

    }
}